import router from './index'
import store from './../store'
import {constantRoutes, mainRoutes} from "@/router/index";
import {constantRouterComponents} from './constantRouterComponents'
import common from "@/router/common";
import api from '@/utils/api.js'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken, setToken, removeToken} from '@/utils/auth' // get token from cookie
import Cookies from 'js-cookie'
import util from '@/utils/util'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const allowList = ['/login', '/error/404']

function loginByCode (code) {
  let state = util.getQueryString('state')
  return new Promise(resolve => {
    api.wxCodeLogin({code, type: '32', state}).then(res => {
      setToken(res.data.accessToken)
      resolve(res.data.accessToken)
    }).catch(err => {
      resolve('')
    })
  })
}
router.beforeEach(async(to, from, next) => {
  // start progress bar
  /*let token = util.getUrlParam('token') // 跳转链接携带token登录
  if (token) {
    store.commit('user/SET_TOKEN', token)
    setToken(token)
  }*/
  NProgress.start()
  let accessToken = api.access_token
  if (accessToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next()
      NProgress.done()
    } else {
      const hasRoute = router.getRoutes().find(item => item.path === to.path)
      if (to.meta.id) {
        await store.commit('user/SET_CURRENT_MENU', to.meta.id)
      }
      if (allowList.includes(to.name) || hasRoute) {
        // 在免登录名单，直接进入
        next()
        if (router.options.isAddDynamicMenuRoutes) return
      }
      if (!router.options.isAddDynamicMenuRoutes) { // 如果已经登记过菜单，就不需要每次都请求后端菜单
        //await store.dispatch('user/getUserInfo')
        await store.dispatch('user/getMenu')
        fnAddDynamicMenuRoutes(store.getters.menuList)
        router.options.isAddDynamicMenuRoutes = true
      }
      const redirect = decodeURIComponent(from.query.redirect || '')
      const routes = router.getRoutes()
      if (routes.filter(item => item.path === to.path).length < 1) {
        router.replace('/')
      } else {
        next({...to, replace: true})
      }
      /*if (to.path === redirect) {
        if (routes.filter(item => item.path == redirect).length < 1) {
          router.replace('/')
        } else {
          next({...to, replace: true})
        }
      } else {
        if (routes.filter(item => item.path === to.path).length < 1) {
          router.replace('/')
        } else {
          // 跳转到目的路由
          next({...to, replace: true})
        }
      }*/
    }
  } else {
    /* has no token*/
    // next()
    if (allowList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
    store.commit('common/updateMainTabs', [{name: 'home', title: '首页'}])
    router.options.isAddDynamicMenuRoutes = false
  }
})

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  let temp = []
  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
    }
    if (menuList[i].path && /\S/.test(menuList[i].path)) {
      // 路由对应的组件
      const component = (constantRouterComponents[menuList[i].path]) || (() => import('@/views/common/404.vue'))
      let route = {
        path: menuList[i].path,
        component: component,
        name: menuList[i].path,
        meta: {
          id: menuList[i].id,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.children = [
      ...common,
      ...routes
    ]
    router.addRoutes([
      mainRoutes,
      {path: '*', redirect: {name: '/error/404'}}
    ])
    store.commit('common/updateDynamicMenuRoutes', mainRoutes.children || [])
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
  }
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
